package com.joesem.sale.client.logic.event

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import com.google.android.material.tabs.TabLayout
import com.google.gson.Gson
import com.jiaxing.sale.client.R
import com.jiaxing.sale.client.databinding.ActivityEventDetailsBinding
import com.jiaxing.sale.client.databinding.LayoutToolbarBinding
import com.joesem.sale.client.base.*
import com.joesem.sale.client.logic.workOrder.WorkOrderCreateActivity
import com.joesem.sale.client.logic.workOrder.WorkOrderDetailsActivity
import com.joesem.sale.client.logic.workOrder.optionCreateContact
import com.joesem.sale.client.logic.workOrder.optionCreateCustomer
import com.joesem.sale.client.network.data.EventDetailsMode
import com.joesem.sale.client.utils.NavigationUtils
import com.joesem.sale.client.utils.activityResult.launcherResult
import com.joesem.sale.client.utils.click
import com.joesem.sale.client.widget.dialog.optionConfirm
import com.joesem.sale.client.widget.dialog.optionDeptUser
import com.joesem.sale.client.widget.dialog.workOrderTypePopup

class EventDetailsActivity : BaseActivity<ActivityEventDetailsBinding>() {

    private val STATUS_WAIT_DISTRIBUTION = "待分配"

    private val STATUS_IN_DISTRIBUTION = "已分配"

    private val STATUS_COMPLETE = "已完成"

    private val eventId: Int
        get() {
            return intent.getIntExtra("eventId", -1)
        }

    private val viewModel by createViewModel<EventViewModel>()

    override fun LayoutToolbarBinding.toolbar(savedInstanceState: Bundle?) {
        visible()
        toolbarTitle.text = "事件详细"
        toolbarTheme()
    }

    override fun ActivityEventDetailsBinding.initView(savedInstanceState: Bundle?) {
        supportFragmentManager.apply {
            val eventReturn = findFragmentById(R.id.fragmentEventDetailsReturn)
            eventReturn?.let { beginTransaction().hide(it).commit() }
        }
        refresh()
        srlRefresh.isRefreshing = true

    }

    override fun ActivityEventDetailsBinding.initListener() {
        srlRefresh.apply {
            setOnRefreshListener {
                refresh()
            }
        }
    }


    private fun refresh() {
        viewModel.getEventDetails(eventId)

    }

    @SuppressLint("SetTextI18n")
    override fun ActivityEventDetailsBinding.initIntent(intent: Any?) {
        when (intent) {
            is EventViewModel.EventDetailsIntent -> {
                srlRefresh.isRefreshing = false
                intent.data?.let { eventData ->
                    llContent.visible()
                    tvStatus.text = eventData.status.orEmpty()
                    tvCustomerName.text = eventData.customer?.name.orEmpty()
                    tvUserNamePhone.text = "联系人：${eventData.contact_name.orEmpty()}"
                    tvUserAddress.text = "地址：${eventData.address.orEmpty()}"
                    btnCall.click { v ->
                        startActivity(Intent(Intent.ACTION_DIAL).apply {
                            data = Uri.parse("tel:${eventData.contact_telephone}")
                        })
                    }
                    btnNavigation.click { v ->
                        if (!eventData.address.isNullOrEmpty())
                            NavigationUtils(this@EventDetailsActivity).navigation(eventData.address)
                    }
                    eventData.logs?.lastOrNull()?.let {
                        cdLogo.visible()
                        tvStateContent.text = it.creator + " " + it.action.orEmpty()
                        tvStateData.text = it.create_time
                    } ?: run {
                        cdLogo.gone()
                    }
                    intentInfo(eventData)
                    when (eventData.status) {
                        STATUS_WAIT_DISTRIBUTION -> {
                            tvPlanAt.text = "创建时间：${eventData.create_time_format}"
                            llButtons.visible()
                            btnCreateOrder.visible()
                            btnSubmit.text = "分配"
                            btnSubmit.click {
                                if (checkCustomerUser(eventData)) {
                                    optionConfirm(
                                        this@EventDetailsActivity,
                                        msg = "确定要分配该事件吗？",
                                        confirmClick = {
                                            optionDeptUser(
                                                this@EventDetailsActivity,
                                                "请选择负责人"
                                            ) {
                                                viewModel.eventAllot(eventId, it.id)
                                            }
                                        })
                                }
                            }
                            btnCreateOrder.click {
                                if (checkCustomerUser(eventData)) {
                                    optionConfirm(
                                        this@EventDetailsActivity,
                                        msg = "确定要创建工单吗？",
                                        confirmClick = {
                                            workOrderTypePopup(it) {
                                                createWorkOrder(it, eventData)
                                            }
                                        })
                                }
                            }
                        }
                        STATUS_IN_DISTRIBUTION -> {
                            tvPlanAt.text = "分配时间：${eventData.update_time}"
                            llButtons.visible()
                            btnCreateOrder.gone()
                            btnSubmit.text = "完成"
                            btnSubmit.click {
                                optionEventReturn(this@EventDetailsActivity, eventId) {
                                    viewModel.actionIntent(EventViewModel.EventDetailsIntent(it))
                                }
                            }
                        }
                        STATUS_COMPLETE -> {
                            tvPlanAt.text = "完成时间：${eventData.update_time_format}"
                            llButtons.gone()
                        }
                        else -> {
                            tvPlanAt.text = "创建时间：${eventData.create_time_format}"
                        }
                    }
                }
            }

            is EventViewModel.EventCreateOrderIntent -> {
                launch<WorkOrderDetailsActivity>("orderId" to intent.data.id)
            }
        }
    }

    private fun intentInfo(data: EventDetailsMode) {
        bind.apply {
            val titles1 = "事件信息"
            val titles2 = "回单信息"
            tbTitle.removeAllTabs()
            tbTitle.addTab(tbTitle.newTab().apply {
                text = titles1
            })
            if (data.status == STATUS_COMPLETE) {
                tbTitle.addTab(tbTitle.newTab().apply {
                    text = titles2
                })
            }
            val eventDetails =
                supportFragmentManager.findFragmentById(R.id.fragmentEventDetailsContent)
            eventDetails?.let {
                (it as EventInfoFragment).refresh(data)
            }
            val eventReturn =
                supportFragmentManager.findFragmentById(R.id.fragmentEventDetailsReturn)
            eventReturn?.let {
                (it as EventReturnFragment).refresh(data)
            }
            tbTitle.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
                override fun onTabSelected(tab: TabLayout.Tab?) {
                    when (tab?.text) {
                        titles1 -> {
                            eventDetails?.let {
                                supportFragmentManager.beginTransaction().apply {
                                    show(it)
                                    eventReturn?.let { it1 -> hide(it1) }
                                }.commit()
                            }
                        }
                        titles2 -> {
                            eventReturn?.let {
                                supportFragmentManager.beginTransaction().apply {
                                    show(it)
                                    eventDetails?.let { it1 -> hide(it1) }
                                }.commit()
                            }
                        }
                    }
                }

                override fun onTabUnselected(tab: TabLayout.Tab?) {

                }

                override fun onTabReselected(tab: TabLayout.Tab?) {

                }
            })

        }

    }

    private fun checkCustomerUser(eventData: EventDetailsMode): Boolean {
        when {
            (eventData.customer_id ?: 0) <= 0 -> {
                optionConfirm(
                    this@EventDetailsActivity,
                    msg = "该客户不存在，是否新建客户"
                ) {
                    optionCreateCustomer(
                        this@EventDetailsActivity,
                        eventId = eventId
                    ) {
                        refresh()
                        bind.srlRefresh.isRefreshing = true
                    }
                }
                return false
            }
            (eventData.customer_user_id ?: 0) <= 0 -> {
                optionConfirm(
                    this@EventDetailsActivity,
                    msg = "客户【${eventData.customer?.name}】还没有联系人，是否要新建联系人"
                ) {
                    optionCreateContact(
                        this@EventDetailsActivity,
                        customerId = eventData.customer_id ?: -1,
                        customerName = eventData.customer?.name.orEmpty(),
                        eventId = eventId
                    ) {
                        refresh()
                        bind.srlRefresh.isRefreshing = true
                    }
                }
                return false
            }
            else -> {
                return true
            }
        }

    }

    private fun createWorkOrder(type: String, eventData: EventDetailsMode) {
        launcherResult<WorkOrderCreateActivity>(
            "type" to type, "eventData" to Gson().toJson(
                eventData
            )
        ) { _: Int, _: Intent? ->
            refresh()
            bind.srlRefresh.isRefreshing = true
        }
    }
}